package org.az.netty_study.p14_netty综合案例2_聊天室.server.handler;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import org.az.netty_study.p14_netty综合案例2_聊天室.message.ChatRequestMessage;
import org.az.netty_study.p14_netty综合案例2_聊天室.message.ChatResponseMessage;
import org.az.netty_study.p14_netty综合案例2_聊天室.message.GroupCreateRequestMessage;
import org.az.netty_study.p14_netty综合案例2_聊天室.message.GroupCreateResponseMessage;
import org.az.netty_study.p14_netty综合案例2_聊天室.server.session.Group;
import org.az.netty_study.p14_netty综合案例2_聊天室.server.session.GroupSession;
import org.az.netty_study.p14_netty综合案例2_聊天室.server.session.GroupSessionFactory;
import org.az.netty_study.p14_netty综合案例2_聊天室.server.session.SessionFactory;

import java.util.Set;

@ChannelHandler.Sharable
public class GroupCreateRequestMessageHandler extends SimpleChannelInboundHandler<GroupCreateRequestMessage> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, GroupCreateRequestMessage msg) throws Exception {
        GroupSession groupSession = GroupSessionFactory.getGroupSession();
        Group group = groupSession.createGroup(msg.getGroupName(), msg.getMembers());
        //建群成功
        if (group == null) {
            ctx.writeAndFlush(new GroupCreateResponseMessage(true, "群聊创建成功"));
            Set<String> members = msg.getMembers();
            for (String member : members) {
                Channel channel = SessionFactory.getSession().getChannel(member);
                if (channel != null) {
                    channel.writeAndFlush(new GroupCreateResponseMessage(true, "你已被拉入群聊"));
                }
            }
        }
        else {
            ctx.writeAndFlush(new GroupCreateResponseMessage(false, "群聊创建失败，该群" + group.getName() + "已存在"));
        }
    }
}
